define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'tongcheng/delivery_order/index' + location.search,
                    // add_url: 'tongcheng/delivery_order/add',
                    // edit_url: 'tongcheng/delivery_order/edit',
                    // del_url: 'tongcheng/delivery_order/del',
                    // multi_url: 'tongcheng/delivery_order/multi',
                    // import_url: 'tongcheng/delivery_order/import',
                    table: 'tongcheng_delivery_order',
                }
            });

            var table = $("#table");

            // 在普通搜索渲染后
            table.on('post-common-search.bs.table', function (event, table) {
                let form = $("form", table.$commonsearch);

                $("input[name='zone_id']", form).addClass("selectpage").data("source", "tongcheng/zone/index").data("params", {"custom[status]": 1}).data("orderBy","id desc");
                $("input[name='module_id']", form).addClass("selectpage").data("source", "tongcheng/module/index").data("params", {"custom[status]": 1}).data("orderBy","id desc");
                $("input[name='rider_id']", form).addClass("selectpage").data("source", "tongcheng/rider/index").data("field", "real_name").data("orderBy","id desc").data("formatItem","{real_name}({user_id})");//.data("params", {"custom[status]": 1})
                $("input[name='user_id']", form).addClass("selectpage").data("source", "user/user/index").data("field", "nickname").data("orderBy","id desc").data("formatItem","{nickname}({id})");

                Form.events.cxselect(form);
                Form.events.selectpage(form);
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'zone_id', title: __('Zone_id'), visible: false},
                        {
                          field: 'zone.name', title: __('Zone.name'), operate: false, formatter: function (value, row, index) {
                            return value + '(' + row.zone_id + ')';
                          }
                        },
                        {field: 'user_id', title: __('User_id'), visible: false},
                        {
                          field: 'user.nickname', title: '用户昵称', operate: false, formatter: function (value, row, index) {
                            return value + '(' + row.user_id + ')';
                          }
                        },
                        {field: 'module_id', title: __('Module_id'), visible: false},
                        // {field: 'module.name', title: __('Module.name'), operate: 'LIKE'},
                        {field: 'rider_id', title: __('Rider_id'), visible: false},
                        {
                          field: 'rider.real_name', title: __('Rider.name'), operate: false, formatter: function (value, row, index) {
                            if (!row.rider_id) {
                              return '-';
                            }
                            return value + '(' + row.rider_id + ')';
                          }
                        },
                        {field: 'order_no', title: __('Order_no'), operate: 'LIKE'},
                        {field: 'type', title: __('Type'), searchList: {"BUY":__('BUY'),"SEND":__('SEND'),"TAKE":__('TAKE'),"WAN":__('WAN'),"1V1":__('1V1')}, formatter: Table.api.formatter.normal},
                        {field: 'is_prebook', title: __('Is_prebook'), searchList: {"0":__('Is_prebook 0'),"1":__('Is_prebook 1')}, formatter: Table.api.formatter.label},
                        {field: 'status', title: __('Status'), searchList: {"0":__('Status 0'),"10":__('Status 10'),"20":__('Status 20'),"25":__('Status 25'),"30":__('Status 30'),"40":__('Status 40'),"99":__('Status 99'),"100":__('Status 100')}, formatter: Table.api.formatter.status},
                        {field: 'refund_status', title: __('refund_status'), searchList: {"0":__('refund_status 0'),"10":__('refund_status 10'),"1":__('refund_status 1'),"2":__('refund_status 2')}, formatter: Table.api.formatter.status},
                        {field: 'appoint_time', title: __('Appoint_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'start_name', title: __('Start_name'), operate: 'LIKE'},
                        {field: 'start_mobile', title: __('Start_mobile'), operate: 'LIKE'},
                        {field: 'start_address', title: __('Start_address'), operate: 'LIKE'},
                        {field: 'start_lng', title: __('Start_lng'), operate: false},
                        {field: 'start_lat', title: __('Start_lat'), operate: false},
                        {field: 'end_name', title: __('End_name'), operate: 'LIKE'},
                        {field: 'end_mobile', title: __('End_mobile'), operate: 'LIKE'},
                        {field: 'end_address', title: __('End_address'), operate: 'LIKE'},
                        {field: 'end_lng', title: __('End_lng'), operate: false},
                        {field: 'end_lat', title: __('End_lat'), operate: false},
                        {field: 'remark', title: __('Remark'), operate: false},
                        {field: 'pickup_code', title: __('Pickup_code'), operate: 'LIKE'},
                        {field: 'distance', title: __('Distance'), operate: false},
                        {field: 'duration', title: __('Duration'), operate: false},
                        {field: 'weight', title: __('Weight'), operate: false},
                        {field: 'amount', title: __('Amount'), operate:'BETWEEN'},
                        {field: 'discount_fee', title: __('Discount_fee'), operate: false},
                        {field: 'actual_amount', title: __('Actual_amount'), operate: false},
                        {field: 'pay_fee', title: __('Pay_fee'), operate: false},
                        {field: 'pay_transaction_id', title: __('Pay_transaction_id'), operate: 'LIKE'},
                        {field: 'pay_time', title: __('Pay_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'receive_time', title: __('Receive_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'arrive_time', title: __('Arrive_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'delivery_time', title: __('Delivery_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'complete_time', title: __('Complete_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'cancel_time', title: __('Cancel_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'cancel_role', title: __('Cancel_role'), searchList: {"CUSTOMER":__('CUSTOMER'),"SYSTEM":__('SYSTEM'),"RIDER":__('RIDER')}, formatter: Table.api.formatter.normal},
                        {field: 'refund_time', title: __('Refund_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'refund_fee', title: __('Refund_fee'), operate: false},
                        {field: 'refund_role', title: __('refund_role'), searchList: {"CUSTOMER":__('refund_role CUSTOMER'),"SYSTEM":__('refund_role SYSTEM'),"RIDER":__('refund_role RIDER')}, formatter: Table.api.formatter.normal},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        // {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {
                            field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons: [
                                {
                                    name: 'detail',
                                    text: '详情',
                                    title: '详情',
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    icon: 'fa fa-list',
                                    url: 'tongcheng/delivery_order/detail',
                                    extend: 'data-area=\'["80%", "80%"]\'',
                                },
                                // 指派
                                {
                                    name: 'riderAssign',
                                    text: '指派',
                                    title: '指派',
                                    classname: 'btn btn-xs btn-info btn-click',
                                    icon: 'fa fa-flag',
                                    visible: function (row) {
                                        return row.status == 10;
                                    },
                                    click: function (e, row) {
                                        console.log('riderAssign', e, row);
                                        Controller.api.showRiderDialog(row.id, row.zone_id);
                                    }
                                },
                                // 转单
                                {
                                    name: 'transfer',
                                    text: '转单',
                                    title: '转单',
                                    classname: 'btn btn-xs btn-info btn-click',
                                    icon: 'fa fa-exchange',
                                    visible: function (row) {
                                        return row.status == 20 && row.refund_status == 0;
                                    },
                                    click: function (e, row) {
                                        console.log('transfer', e, row);
                                        Controller.api.showRiderDialog(row.id, row.zone_id, 'transfer');
                                    }
                                },
                                // 到达取货点
                                {
                                    name: 'riderArrive',
                                    text: '到达取货点',
                                    title: '到达取货点',
                                    classname: 'btn btn-xs btn-info btn-click',
                                    icon: 'fa fa-street-view',
                                    visible: function (row) {
                                        return row.status == 20 && row.refund_status == 0;
                                    },
                                    click: function (e, row) {
                                        console.log('riderArrive', e, row);
                                        Controller.api.riderArrive(row.id, row.zone_id);
                                    }
                                },
                                // 开始配送
                                {
                                    name: 'riderDelivering',
                                    text: '开始配送',
                                    title: '开始配送',
                                    classname: 'btn btn-xs btn-info btn-click',
                                    icon: 'fa fa-truck',
                                    visible: function (row) {
                                        return row.status == 25 && row.refund_status == 0;
                                    },
                                    click: function (e, row) {
                                        console.log('riderDelivering', e, row);
                                        Controller.api.riderDelivering(row.id, row.zone_id);
                                    }
                                },
                                // 完成配送
                                {
                                    name: 'complete',
                                    text: '完成配送',
                                    title: '完成配送',
                                    classname: 'btn btn-xs btn-success btn-click',
                                    icon: 'fa fa-flag-checkered',
                                    visible: function (row) {
                                        return row.status == 30 && row.refund_status == 0;
                                    },
                                    click: function (e, row) {
                                        console.log('complete', e, row);
                                        Controller.api.complete(row.id, row.zone_id);
                                    }
                                },

                                // 同意退款
                                {
                                    name: 'refundAccept',
                                    text: '同意退款',
                                    title: '同意退款',
                                    classname: 'btn btn-xs btn-success btn-click',
                                    icon: 'fa fa-check-circle',
                                    visible: function (row) {
                                        return row.refund_status == 10;
                                    },
                                    click: function (e, row) {
                                        console.log('refundAccept', e, row);
                                        Controller.api.refundAccept(row.id);
                                    }
                                },
                                // 拒绝退款
                                {
                                    name: 'refundReject',
                                    text: '拒绝退款',
                                    title: '拒绝退款',
                                    classname: 'btn btn-xs btn-danger btn-click',
                                    icon: 'fa fa-times-circle',
                                    visible: function (row) {
                                        return row.refund_status == 10;
                                    },
                                    click: function (e, row) {
                                        console.log('refundReject', e, row);
                                        Controller.api.refundReject(row.id);
                                    }
                                },


                            ]
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            // 刷新页面
            refresh: function (timeout = 1500) {
                setTimeout(() => {
                  console.log('refresh');
                  window.location.reload();
                }, timeout);
            },

            // 骑手列表弹窗
            showRiderDialog: function (order_id, zone_id, type = 'assign') {
                Fast.api.open('tongcheng/rider/online?zone_id=' + zone_id, '在线骑手列表', {
                    callback: function (data) {
                        console.log('showRiderDialog callback', data);
                        var rider_id = data.rider.user_id;
                        // 指派骑手
                        if (type == 'assign') {
                            Controller.api.riderAssign(order_id, rider_id);
                        } else if (type == 'transfer') {// 转单
                            Controller.api.transfer(order_id, rider_id);
                        }
                    }
                });
            },
            // 指派骑手
            riderAssign: function (order_id, rider_id) {
                var url = 'tongcheng/delivery_order/riderAssign';
                var data = {
                    order_id: order_id,
                    rider_id: rider_id
                };
                Fast.api.ajax({
                    url: url,
                    data: data,
                    loading: true,
                    success: function (result) {
                        Layer.closeAll();
                        Toastr.success(result.msg);
                        Controller.api.refresh();
                    }
                });
            },
            // 指派骑手
            transfer: function (order_id, rider_id) {
                var url = 'tongcheng/delivery_order/transfer';
                var data = {
                    order_id: order_id,
                    rider_id: rider_id
                };
                Fast.api.ajax({
                    url: url,
                    data: data,
                    loading: true,
                    success: function (result) {
                        Layer.closeAll();
                        Toastr.success(result.msg);
                        Controller.api.refresh();
                    }
                });
            },
            // 到达取货点
            riderArrive: function (order_id) {
                layer.confirm('确认到达取货点？', {
                    btn: ['确认', '取消'],
                    icon: 3,
                    title: '提示'
                }, (index) => {
                    var url = 'tongcheng/delivery_order/riderArrive?ids=' + order_id;
                    var data = {
                      order_id: order_id,
                    };
                    Fast.api.ajax({
                        url: url,
                        data: data,
                        loading: true,
                        success: (result) => {
                            layer.close(index);
                            Layer.closeAll();
                            Toastr.success(result.msg);
                            Controller.api.refresh();
                        }
                    });
                }, (index) => {
                    layer.close(index);
                });


            },
            // 开始配送
            riderDelivering: function (order_id) {
                layer.confirm('确认开始配送？', {
                    btn: ['确认', '取消'],
                    icon: 3,
                    title: '提示'
                }, (index) => {
                    var url = 'tongcheng/delivery_order/riderDelivering?ids=' + order_id;
                    var data = {
                        order_id: order_id,
                    };
                    Fast.api.ajax({
                        url: url,
                        data: data,
                        loading: true,
                        success: function (result) {
                            Layer.closeAll();
                            Toastr.success(result.msg);
                            Controller.api.refresh();
                        }
                    });
                }, (index) => {
                  layer.close(index);
                });
            },
            // 完成配送
            complete: function (order_id) {
                layer.confirm('确认完成配送？', {
                    btn: ['确认', '取消'],
                    icon: 3,
                    title: '提示'
                }, (index) => {
                    var url = 'tongcheng/delivery_order/complete?ids=' + order_id;
                    var data = {
                        order_id: order_id,
                    };
                    Fast.api.ajax({
                        url: url,
                        data: data,
                        loading: true,
                        success: function (result) {
                            Layer.closeAll();
                            Toastr.success(result.msg);
                            Controller.api.refresh();
                        }
                    });
                }, (index) => {
                  layer.close(index);
                });
            },
            // 取消订单
            cancel: function (order_id) {
                layer.confirm('确认取消订单？', {
                    btn: ['确认', '取消'],
                    icon: 3,
                    title: '提示'
                }, (index) => {
                    var url = 'tongcheng/delivery_order/cancel?ids=' + order_id;
                    var data = {
                        order_id: order_id,
                    };
                    Fast.api.ajax({
                        url: url,
                        data: data,
                        loading: true,
                        success: function (result) {
                            Layer.closeAll();
                            Toastr.success(result.msg);
                            Controller.api.refresh();
                        }
                    });
                }, (index) => {
                  layer.close(index);
                });
            },
            // 同意退款
            refundAccept: function (order_id) {
                layer.confirm('确认同意退款？', {
                    btn: ['确认', '取消'],
                    icon: 3,
                    title: '提示'
                }, (index) => {
                    var url = 'tongcheng/delivery_order/refundAccept?ids=' + order_id;
                    var data = {
                        order_id: order_id,
                    };
                    Fast.api.ajax({
                        url: url,
                        data: data,
                        loading: true,
                        success: function (result) {
                            Layer.closeAll();
                            Toastr.success(result.msg);
                            Controller.api.refresh();
                        }
                    });
                }, (index) => {
                  layer.close(index);
                });
            },
            // 拒绝退款
            refundReject: function (order_id) {
                layer.prompt({
                  formType: 2,
                  title: '拒绝退款，填写拒绝理由',
                  area: ['400px', '150px'],
                }, function (value, index, elem) {
                    var url = 'tongcheng/delivery_order/refundReject?ids=' + order_id;
                    var data = {
                      order_id: order_id,
                      reject_remark: value
                    };
                    Fast.api.ajax({
                      url: url,
                      data: data,
                      loading: true,
                      success: function (result) {
                        Layer.closeAll();
                        Toastr.success(result.msg);
                        Controller.api.refresh();
                      }
                    });
                });
            },

        }
    };

    ctrl = Controller;
    return Controller;
});
